#-------------------------------------------------------------------------------
#   Trakt Interface
#   Wraps calls to the trakt.tv API
#   
#   http://ttcp.codeplex.com
#-------------------------------------------------------------------------------
import json
import hashlib
import mechanize

#-------------------------------------------------------------------------------
# String Constants
baseURL = "http://api.trakt.tv/"
movieWatchlistURL = baseURL + "user/watchlist/movies.json/"
unwatchlistMovieURL = baseURL + "movie/unwatchlist.json/"


#-------------------------------------------------------------------------------
# SHA1 hash
def hash(value):
    m = hashlib.sha1()
    m.update(value)
    return m.hexdigest()


#-------------------------------------------------------------------------------
# construct the url
def makeURL(url, apiKey, username):
    result = url + apiKey
    if username != "":
        result += "/" + username
        
    return result


#-------------------------------------------------------------------------------
# get the movie watchlist
def movieWatchlist(username, password, apiKey):
    url = makeURL(movieWatchlistURL, apiKey, username)

    postdata = {'username': username, 'password': hash(password)}
    postdata_json = json.dumps(postdata)
    
    req = mechanize.Request(url, postdata_json)
    res_stream = mechanize.urlopen(req)
    response = res_stream.read()
    
    movies = json.loads(response)
    return movies


#-------------------------------------------------------------------------------
def removeMovieFromWatchlist(username, password, apiKey, title, year, imdb_id):
    url = makeURL(unwatchlistMovieURL, apiKey, "")

    postdata = {    'username': username,
                    'password': hash(password),
                    'movies':   [{ 'title': title,
                                    'year': year,
                                    'imdb_id': imdb_id
                                }]
                }
    postdata_json = json.dumps(postdata)
    
    req = mechanize.Request(url, postdata_json)
    res_stream = mechanize.urlopen(req)
    response = res_stream.read()


#-------------------------------------------------------------------------------

  


